import json

import requests as rq

sess = rq.session()


def isLogin(authorization=""):
    profile = sess.get("https://www.lintcode.com/new/api/accounts/profile/",
                       headers={"authorization": "Bearer " + authorization})

    json_body = json.loads(profile.text)
    if json_body.get("data") is None:
        print("没有登录！")
        return False
    else:
        print("已经登录！")
        return True


def Login(username, password):
    data = '{"account":"' + username + '","password":"' + password + '","signup_source":1}'
    body = sess.post("https://www.lintcode.com/v2/api/accounts/signin/", data=data,
                     headers={"content-type": "application/json;charset=UTF-8"})
    json_body = json.loads(body.text)
    print(json_body)
    if json_body.get("success") is True:
        # 说明请求成功
        nickname = json_body.get("data").get("nickname")
        print("登录成功！{}".format(nickname))
        token = json_body.get("data").get("access")
        print(token)
        return token
    else:
        # 说明请求失败
        print("登录失败！")
        return None


token = Login("XXX", "XXX")
if token is not None:
    isLogin(token)
else:
    isLogin()
